import pymysql
from database import get_db_connection

class OrderManager:
    def __init__(self):
        self.db = None

    def get_db_connection(self):
        """获取数据库连接"""
        return get_db_connection()

    def get_shopping_cart(self, username):
        """获取购物车内容"""
        db = None
        try:
            db = self.get_db_connection()
            cursor = db.cursor()
            sql = "SELECT * FROM SHOPPINGCART WHERE username = %s"
            cursor.execute(sql, (username,))
            res = cursor.fetchall()
            return res if res else None
        except pymysql.Error as e:
            print(f"Database error: {e}")
            return None
        finally:
            if db:
                db.close()

    def add_to_cart(self, username, restaurant, dishname, price, img_res):
        """添加菜品到购物车"""
        db = None
        try:
            db = self.get_db_connection()
            cursor = db.cursor()
            sql = """
                INSERT INTO SHOPPINGCART (username, restaurant, dishname, price, img_res)
                VALUES (%s, %s, %s, %s, %s)
            """
            cursor.execute(sql, (username, restaurant, dishname, price, img_res))
            db.commit()
            return True
        except pymysql.Error as e:
            print(f"Database error: {e}")
            db.rollback()
            return False
        finally:
            if db:
                db.close()

    def checkout_order(self, username, restaurant, dishname, price, img_res, mode):
        """结算订单"""
        # 这里可以扩展实际的结算逻辑
        print("堂食" if mode == '1' else "外送")
        return True

    def get_order_comments(self, username):
        """获取用户的订单评论"""
        db = None
        try:
            db = self.get_db_connection()
            cursor = db.cursor()
            sql = "SELECT * FROM ORDER_COMMENT WHERE username = %s"
            cursor.execute(sql, (username,))
            res = cursor.fetchall()
            return res if res else None
        except pymysql.Error as e:
            print(f"Database error: {e}")
            return None
        finally:
            if db:
                db.close()

    def sort_orders_by_time(self, username):
        """按时间排序订单"""
        db = None
        try:
            db = self.get_db_connection()
            cursor = db.cursor()
            sql = "SELECT * FROM ORDER_COMMENT WHERE username = %s ORDER BY transactiontime DESC"
            cursor.execute(sql, (username,))
            res = cursor.fetchall()
            return res if res else None
        except pymysql.Error as e:
            print(f"Database error: {e}")
            return None
        finally:
            if db:
                db.close()

    def sort_orders_by_price(self, username):
        """按价格排序订单"""
        db = None
        try:
            db = self.get_db_connection()
            cursor = db.cursor()
            sql = "SELECT * FROM ORDER_COMMENT WHERE username = %s ORDER BY cost ASC"
            cursor.execute(sql, (username,))
            res = cursor.fetchall()
            return res if res else None
        except pymysql.Error as e:
            print(f"Database error: {e}")
            return None
        finally:
            if db:
                db.close()

    def get_unfinished_orders(self, username):
        """获取未完成订单"""
        db = None
        try:
            db = self.get_db_connection()
            cursor = db.cursor()
            sql = "SELECT * FROM ORDER_COMMENT WHERE username = %s AND isFinished = 0"
            cursor.execute(sql, (username,))
            res = cursor.fetchall()
            return res if res else None
        except pymysql.Error as e:
            print(f"Database error: {e}")
            return None
        finally:
            if db:
                db.close()

    def confirm_order(self, orderID, dishname, restaurant):
        """确认收货并更新销量"""
        db = None
        try:
            db = self.get_db_connection()
            cursor = db.cursor()
            sql1 = "UPDATE ORDER_COMMENT SET isFinished = 1, text = '' WHERE orderID = %s"
            cursor.execute(sql1, (orderID,))
            sql2 = "UPDATE DISHES SET sales = sales + 1 WHERE dishname = %s AND restaurant = %s"
            cursor.execute(sql2, (dishname, restaurant))
            db.commit()
            return True
        except pymysql.Error as e:
            print(f"Database error: {e}")
            db.rollback()
            return False
        finally:
            if db:
                db.close()

    def get_my_comments(self, username):
        """获取我的评论"""
        db = None
        try:
            db = self.get_db_connection()
            cursor = db.cursor()
            sql = "SELECT * FROM ORDER_COMMENT WHERE username = %s AND isFinished = 1 AND text != ''"
            cursor.execute(sql, (username,))
            res = cursor.fetchall()
            return res if res else None
        except pymysql.Error as e:
            print(f"Database error: {e}")
            return None
        finally:
            if db:
                db.close()